<template>
  <div>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>参数分类</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图 -->
    <el-card>
      <!-- 提示信息 -->
      <el-alert title="注意：只允许为第三级分类设置相关参数！" type="warning" show-icon :closable="false"> </el-alert>
      <!-- 选择商品分类 -->
      <el-row class="row-box">
        <el-col>
          <span>选择商品分类：</span>
          <!-- 级联选择器 -->
          <el-cascader
            style="width:30%"
            clearable
            v-model="selectedKeys"
            :options="cateList"
            expandTrigger="hover"
            :props="propsCascader"
            @change="cateChanged"
          ></el-cascader>
        </el-col>
      </el-row>
      <!-- tabs页签区域 -->
      <el-tabs v-model="activeName" @tab-click="handleClick">
        <el-tab-pane label="动态参数" name="many">
          <el-button type="primary" size="mini" :disabled="disBtn" @click="openAddDailog">添加参数</el-button>
          <!-- 动态表格区域 -->
          <el-table :data="manyTabList" style="width: 100%" border stripe>
            <el-table-column type="expand" width="50">
              <template slot-scope="scope">
                <el-tag
                  v-for="(item, index) in scope.row.attr_vals"
                  :key="index"
                  closable
                  :disable-transitions="false"
                  @close="handleClose(index, scope.row)"
                  >{{ item }}</el-tag
                >
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
                <!-- <div>
                  {{ scope.row.attr_vals }}
                </div> -->
              </template>
            </el-table-column>
            <el-table-column type="index" width="50"> </el-table-column>
            <el-table-column prop="attr_name" label="参数名称"> </el-table-column>

            <el-table-column label="操作">
              <template slot-scope="scope">
                <!-- 修改 -->
                <el-button type="primary" icon="el-icon-edit" size="mini" @click="openEditDialog(scope.row.attr_id)">编辑</el-button>
                {{ scope.row.attr_id }}

                <!-- 删除 -->
                <el-button type="danger" icon="el-icon-delete" size="mini" @click="openDel(scope.row.attr_id)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <el-tab-pane label="静态属性" name="only">
          <el-button type="primary" size="mini" :disabled="disBtn" @click="openAddDailog">添加属性</el-button>
          <!-- 静态表格区域 -->
          <el-table :data="onlyTabList" style="width: 100%" border stripe>
            <el-table-column type="expand" width="50">
              <template slot-scope="scope">
                <el-tag
                  v-for="(item, index) in scope.row.attr_vals"
                  :key="index"
                  closable
                  :disable-transitions="false"
                  @close="handleClose(index, scope.row)"
                  >{{ item }}</el-tag
                >
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
                <!-- <div>
                  {{ scope.row.attr_vals }}
                </div> -->
              </template>
            </el-table-column>
            <el-table-column type="index" width="50"> </el-table-column>
            <el-table-column prop="attr_name" label="参数名称"> </el-table-column>

            <el-table-column label="操作">
              <template slot-scope="scope">
                <!-- 修改 -->
                <el-button type="primary" icon="el-icon-edit" size="mini" @click="openEditDialog(scope.row.attr_id)">编辑</el-button>
                <!-- 删除 -->
                <el-button type="danger" icon="el-icon-delete" size="mini" @click="openDel(scope.row.attr_id)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
      <!--添加 dailog -->
      <el-dialog :title="'添加' + titleText" :visible.sync="addDialogVisible" width="50%" @close="closeAddDailog">
        <el-form :model="addForm" :rules="addRules" ref="addRef" label-width="100px" class="demo-ruleForm">
          <el-form-item :label="titleText" prop="attr_name">
            <el-input v-model="addForm.attr_name"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="addDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="addinfo">确 定</el-button>
        </span>
      </el-dialog>
      <!--编辑 dailog -->
      <el-dialog :title="'编辑' + titleText" :visible.sync="editDialogVisible" width="50%" @close="closeeditDailog">
        <el-form :model="editForm" :rules="addRules" ref="editRef" label-width="100px" class="demo-ruleForm">
          <el-form-item :label="titleText" prop="attr_name">
            <el-input v-model="editForm.attr_name"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="editDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="editinfo">确 定</el-button>
        </span>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
export default {
  data() {
    return {
      cateList: [],
      selectedKeys: [],
      propsCascader: {
        value: 'cat_id',
        label: 'cat_name',
        children: 'children'
      },
      activeName: 'many',
      manyTabList: [],
      onlyTabList: [],
      //   addDialogVisible 控制显示
      addDialogVisible: false,
      addForm: {
        attr_name: ''
      },
      addRules: { attr_name: [{ required: true, message: '请选择活动区域', trigger: 'change' }] },
      // 编辑显示
      editDialogVisible: false,
      editForm: {}
    }
  },
  methods: {
    async getCateList() {
      const { data: res } = await this.$http.get('categories')
      //   console.log(res)
      if (res.meta.status !== 200) {
        return this.$message.error('获取商品分类数据列表失败!')
      }
      this.$message.success('获取商品分类数据列表成功!')
      this.cateList = res.data
      //   console.log(this.cateList)
    },
    cateChanged() {
      this.getParams()
    },
    // tabs页签区域点击事件
    handleClick() {
      console.log(this.activeName)
      this.getParams()
    },
    async getParams() {
      if (this.selectedKeys.length !== 3) {
        this.selectedKeys = []
        this.manyTabList = []
        this.onlyTabList = []
        return false
      }
      console.log(this.selectedKeys)
      const { data: res } = await this.$http.get(`categories/${this.cateId}/attributes`, {
        params: { sel: this.activeName }
      })
      if (res.meta.status !== 200) {
        return this.$message.error('获取参数列表失败！')
      }
      console.log(res.data)
      res.data.forEach((item) => {
        item.attr_vals = item.attr_vals ? item.attr_vals.split(' ') : []
        // 控制文本框的显示
        item.inputVisible = false
        // 文本框输入的值
        item.inputValue = ''
      })

      if (this.activeName === 'many') {
        this.manyTabList = res.data
      }
      this.onlyTabList = res.data
    },
    // 点击添加add对话框
    openAddDailog() {
      this.addDialogVisible = true
    },
    closeAddDailog() {
      this.$refs.addRef.resetFields()
    },
    // 点击添加 addinfo
    addinfo() {
      this.$refs.addRef.validate(async (valid) => {
        if (!valid) {
          return false
        }
        const { data: res } = await this.$http.post(`categories/${this.cateId}/attributes`, {
          attr_name: this.addForm.attr_name,
          attr_sel: this.activeName
        })
        if (res.meta.status !== 201) {
          return this.$message.error('添加失败!')
        }
        console.log(res.data)
        this.addDialogVisible = false
        this.getParams()
      })
    },
    // 点击编辑 openEditDialog
    async openEditDialog(attrid) {
      this.editDialogVisible = true
      const { data: res } = await this.$http.get(`categories/${this.cateId}/attributes/${attrid}`, {
        params: { attr_sel: this.activeName }
      })
      if (res.meta.status !== 200) {
        return this.$message.error('获取参数失败!')
      }
      //   console.log(res.data)
      this.editForm = res.data
    },
    // 关闭重置closeeditDailog
    closeeditDailog() {
      this.$refs.editRef.resetFields()
    },
    // 提交编辑
    editinfo() {
      this.$refs.editRef.validate(async (valid) => {
        if (!valid) {
          return false
        }
        const { data: res } = await this.$http.put(`categories/${this.cateId}/attributes/${this.editForm.attr_id}`, {
          attr_name: this.editForm.attr_name,
          attr_sel: this.activeName
        })
        if (res.meta.status !== 200) {
          return this.$message.error('编辑失败!')
        }
        console.log(res.data)
        this.$message.success('编辑成功!')
        this.editDialogVisible = false
        this.getParams()
      })
    },
    // 点击确定按钮编辑用户
    async openDel(attrid) {
      // console.log(id)
      const confirmResult = await this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch((err) => {
        return err
      })
      console.log(confirmResult)
      // 如果用户确认删除返回结果为字符串confirm
      // 如果用户取消删除返回结果为字符串cancel
      if (confirmResult !== 'confirm') {
        return this.$message.info('已取消删除')
      }
      // console.log('queren')
      const { data: res } = await this.$http.delete(`categories/${this.cateId}/attributes/${attrid}`)
      console.log(res)
      if (res.meta.status !== 200) {
        return this.$message.error('删除失败!')
      }
      this.$message.success('删除成功!')
      this.getParams()
    },
    // 当鼠标点击或者键盘enter触发事件
    handleInputConfirm(row) {
      //   console.log('ok')
      //   console.log(row)

      if (row.inputValue.trim().length === 0) {
        row.inputValue = ''
        row.inputVisible = false
        return true
      }
      //   如果没有return 则证明输入有内容,进一步处理
      row.attr_vals.push(row.inputValue.trim())
      row.inputValue = ''
      row.inputVisible = false
      //   此时再发起请求将前端数据传入后台
      this.saveAttrVal(row)
    },
    // 将对 attr_vals 的操作，保存到数据库
    async saveAttrVal(row) {
      const { data: res } = await this.$http.put(`categories/${this.cateId}/attributes/${row.attr_id}`, {
        attr_name: row.attr_name,
        attr_sel: row.attr_sel,
        attr_vals: row.attr_vals.join(' ')
      })
      if (res.meta.status !== 200) {
        return this.$message.error('修改参数失败!')
      }
      //   console.log(res.data)
    },
    // 删除参数或者属性
    handleClose(index, row) {
      row.attr_vals.splice(index, 1)
      this.saveAttrVal(row)
    },
    showInput(row) {
      row.inputVisible = true
      // 让文本框自动获得焦点
      // $nextTick 方法的作用，就是当页面上元素被重新渲染之后，才会指定回调函数中的代码
      this.$nextTick((_) => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    }
  },
  computed: {
    disBtn() {
      if (this.selectedKeys.length !== 3) {
        return true
      }
      return false
    },
    cateId() {
      if (this.selectedKeys.length === 3) {
        return this.selectedKeys[2]
      }
      return null
    },

    titleText() {
      if (this.activeName === 'many') {
        return '动态参数'
      } else {
        return '静态属性'
      }
    }
  },
  created() {
    this.getCateList()
  }
}
</script>

<style lang="scss" scoped>
.row-box {
  margin-top: 15px;
}
.el-tag {
  margin: 10px;
}
.input-new-tag {
  width: 120px;
}
</style>
